package com.cdu.guoxinan.www.smartcom.service.impl;

import com.cdu.guoxinan.www.smartcom.domian.dto.OrderDTO;
import com.cdu.guoxinan.www.smartcom.domian.pojo.Order;
import com.cdu.guoxinan.www.smartcom.domian.pojo.OrderItem;
import com.cdu.guoxinan.www.smartcom.domian.pojo.Resident;
import com.cdu.guoxinan.www.smartcom.mapper.OrderMapper;
import com.cdu.guoxinan.www.smartcom.mapper.ResidentMapper;
import com.cdu.guoxinan.www.smartcom.service.OrderService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Service
public class OrderServiceImpl implements OrderService {
    
    @Resource
    private OrderMapper orderMapper;
    
    @Resource
    private ResidentMapper residentMapper;
    
    @Override
    @Transactional
    public Order createOrder(OrderDTO orderDTO) {
        // 根据用户ID获取居民信息
        Resident resident = residentMapper.selectByUserId(orderDTO.getUserId());
        if (resident == null) {
            throw new RuntimeException("未找到对应的居民信息");
        }
        
        // 生成订单ID（使用时间戳）
        Long orderId = System.currentTimeMillis();
        
        // 创建订单对象
        Order order = new Order();
        order.setOrderId(orderId);
        order.setResidentId(resident.getResidentId());
        order.setTotalAmount(orderDTO.getTotalAmount());
        order.setStatus(1); // 1-待支付
        order.setOrderTime(new Date());
        order.setDeliveryAddress(orderDTO.getDeliveryAddress());
        order.setPhoneNumber(orderDTO.getPhoneNumber());
        order.setRemark(orderDTO.getRemark());
        
        // 插入订单
        orderMapper.insertOrder(order);
        
        // 插入订单明细
        if (orderDTO.getItems() != null && !orderDTO.getItems().isEmpty()) {
            for (OrderDTO.OrderItemDTO itemDTO : orderDTO.getItems()) {
                OrderItem orderItem = new OrderItem();
                orderItem.setItemId(System.currentTimeMillis() + (long)(Math.random() * 1000));
                orderItem.setOrderId(orderId);
                orderItem.setProductId(itemDTO.getProductId());
                orderItem.setQuantity(itemDTO.getQuantity());
                orderItem.setPrice(itemDTO.getPrice());
                
                orderMapper.insertOrderItem(orderItem);
            }
        }
        
        return order;
    }
    
    @Override
    public List<Order> getOrdersByUserId(Long userId) {
        return orderMapper.selectOrdersByUserId(userId);
    }
    
    @Override
    public List<OrderItem> getOrderItemsByOrderId(Long orderId) {
        return orderMapper.selectOrderItemsByOrderId(orderId);
    }
    
    @Override
    @Transactional
    public boolean payOrder(Long orderId) {
        // 查询订单
        Order order = orderMapper.selectOrderByOrderId(orderId);
        if (order == null) {
            return false;
        }
        
        // 检查订单状态是否为待支付
        if (order.getStatus() != 1) {
            return false;
        }
        
        // 更新订单状态为已支付
        order.setStatus(2); // 2-已支付
        int result = orderMapper.updateOrderStatus(orderId, 2);
        return result > 0;
    }
    
    @Override
    @Transactional
    public boolean cancelOrder(Long orderId) {
        // 查询订单
        Order order = orderMapper.selectOrderByOrderId(orderId);
        if (order == null) {
            return false;
        }
        
        // 检查订单状态是否为待支付
        if (order.getStatus() != 1) {
            return false;
        }
        
        // 更新订单状态为已取消
        order.setStatus(3); // 3-已取消
        int result = orderMapper.updateOrderStatus(orderId, 3);
        return result > 0;
    }
    
    @Override
    @Transactional
    public boolean deleteOrder(Long orderId) {
        // 查询订单
        Order order = orderMapper.selectOrderByOrderId(orderId);
        if (order == null) {
            return false;
        }
        
        // 检查订单状态是否为已完成或已取消
        if (order.getStatus() != 3 && order.getStatus() != 4) {
            return false;
        }
        
        try {
            // 先删除订单明细
            orderMapper.deleteOrderItemsByOrderId(orderId);
            
            // 再删除订单
            int result = orderMapper.deleteOrderByOrderId(orderId);
            return result > 0;
        } catch (Exception e) {
            // 如果删除失败，事务会自动回滚
            throw new RuntimeException("删除订单失败：" + e.getMessage());
        }
    }
    
    @Override
    public List<Order> getAllOrdersWithPagination(int page, int limit, String sortField, String sortOrder) {
        int offset = (page - 1) * limit;
        return orderMapper.selectAllOrdersWithUser(offset, limit, sortField, sortOrder);
    }
    
    @Override
    public int countAllOrders() {
        return orderMapper.countAllOrders();
    }
    
    @Override
    @Transactional
    public boolean completeOrder(Long orderId) {
        // 查询订单
        Order order = orderMapper.selectOrderByOrderId(orderId);
        if (order == null) {
            return false;
        }
        
        // 检查订单状态是否为已支付
        if (order.getStatus() != 2) {
            return false;
        }
        
        // 更新订单状态为已完成
        order.setStatus(4); // 4-已完成
        int result = orderMapper.updateOrderStatus(orderId, 4);
        return result > 0;
    }
} 